import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth.js'
import router from '@/router/index.js'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  // baseURL: '/api',
  baseURL: import.meta.env.VITE_BASE_URL,
  // baseURL: 'http://111.202.231.146:8016/jcy/prod-api',
  // baseURL: '/dev-api',
  // 超时
  // timeout: 10000,
})

service.interceptors.request.use((config) => {
  if (useAuthStore().token) {
    config.headers[import.meta.env.VITE_SYS_TOKEN_KEY] = useAuthStore().token
  }
  return config
})
service.interceptors.response.use(
  (res) => {
    // 状态码
    const code = res.data.code || 200
    // 错误信息
    const msg = res.data.msg || ''
    if (code === 6002) {
      // token过期
      useAuthStore().setToken(null)
      window.location.reload()
      ElMessage({
        message: msg,
        type: 'error',
      })
    } else if (code !== 200) {
      ElMessage({
        message: msg,
        type: 'error',
      })
      return Promise.reject(new Error(msg))
    } else {
      return Promise.resolve(res.data)
    }
  },
  (error) => {
    const msg = error.message
    ElMessage({
      message: msg,
      type: 'error',
    })
    return Promise.reject(error)
  },
)

export default service
